import { _decorator, Component, Enum, EventTouch, find, instantiate, Node, Prefab } from 'cc';
import { WEAPON } from '../AshFramework/Datas/Constant';
import { PrefsManager } from '../AshFramework/Managers/PrefsManager';
import { ResourceUtil } from '../AshFramework/Utils/ResourceUtil';
import { GameManager } from './GameManager';
import { HintController } from './HintController';
import { ZTool } from '../AshFramework/Utils/ZTool';
import { GameData } from './GameData';
import { Shop } from './Shop';
import { AudioManager, Audios } from '../AshFramework/Managers/AudioManager';
import { TLWLSJ_UIManager } from './UIManager';
const { ccclass, property } = _decorator;

@ccclass('WeaponItem')
export class WeaponItem extends Component {

    @property({ type: Enum(WEAPON) })
    Type: WEAPON = WEAPON.自动手枪;

    @property
    Price: number = 0;

    Have: Node = null;
    NoHave: Node = null;

    protected onLoad(): void {
        this.Have = find("拥有/拥有", this.node);
        this.NoHave = find("拥有/未拥有", this.node);
        this.Have.on(Node.EventType.TOUCH_END, this.onHaveTouchEnd, this);
        this.NoHave.on(Node.EventType.TOUCH_END, this.onNoHaveTouchEnd, this);
    }

    protected start(): void {
        this.show();
    }

    show() {
        if (PrefsManager.Instance.userData.HaveWeapon.findIndex(e => e == this.Type) == -1) {
            this.Have.active = false;
            this.NoHave.active = true;
        } else {
            this.Have.active = true;
            this.NoHave.active = false;
        }
    }

    onHaveTouchEnd(event: EventTouch) {
        ResourceUtil.LoadPrefab("UI/Hint").then((prefab: Prefab) => {
            const node: Node = instantiate(prefab);
            node.parent = GameManager.Instance.Canvas;
            const hint: string = `已经拥有！`;
            node.getComponent(HintController).showHint(hint);
        })
    }

    onNoHaveTouchEnd(event: EventTouch) {
        AudioManager.PlaySound(Audios.ButtonClick);
        let hint: string = "";
        if (PrefsManager.Instance.userData.Gold >= this.Price) {
            PrefsManager.Instance.userData.HaveWeapon.push(this.Type);
            Shop.Instance.showGold(this.Price);
            GameData.addWeaponByType(this.Type);
            GameData.DateSave();
            PrefsManager.Instance.saveData();
            TLWLSJ_UIManager.Instance.showWeapon();
            this.show();
            hint = `购买成功！恭喜获得：` + ZTool.GetEnumKeyByValue(WEAPON, this.Type);
        } else {
            hint = `余额不足！`;
        }
        ResourceUtil.LoadPrefab("UI/Hint").then((prefab: Prefab) => {
            const node: Node = instantiate(prefab);
            node.parent = GameManager.Instance.Canvas;
            node.getComponent(HintController).showHint(hint);
        })
    }
}


